import { Inject, Provide } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { News } from '../../entity/news.entity';
import { LessThan, MoreThan, Repository } from 'typeorm';
import type { IResponse } from '../../interface';

@Provide()
export class NewService {

  @Inject()
  ctx: Context;

  @InjectEntityModel(News)
  entityModel: Repository<News>

  async create(n: News): Promise<News> {
    return this.entityModel.save(n);
  }

  async findAll(pageNo: number, pageSize: number): Promise<any> {
    const skip = (pageNo - 1) * pageSize;
    const [data, total] = await this.entityModel.findAndCount({
      where: {
        isDeleted: 0
      },
      take: pageSize,
      skip,
    });
    if (data) {
      return {
        success: true,
        data,
        total,
      }
    }
    return {
      success: true,
      data,
      total
    };
  }

  // 根据类型查询
  async findByType(type: string, pageNo: number, pageSize: number): Promise<any> {
    const skip = (pageNo - 1) * pageSize;
    const [data, total] = await this.entityModel.findAndCount({
      where: {
        type,
        isDeleted: 0
      },
      take: pageSize,
      skip,
    });
    return {
      success: true,
      data,
      total
    };
  }

  async findOne(uuid: string): Promise<IResponse<{
    data: News,
    last: News,
    next: News,
  }>> {
    const res = await this.entityModel.findOneBy({ uuid, isDeleted: 0 });
    const last = await this.entityModel.find({
      where: {
        createdTime: LessThan(res.createdTime),
        isDeleted: 0,
      },
      take: 1,
      order: {
        createdTime: 'DESC',
      }
    });
    const next = await this.entityModel.find({
      where: {
        createdTime: MoreThan(res.createdTime),
        isDeleted: 0,
      },
      take: 1,
      order: {
        createdTime: 'DESC',
      }
    });
    if (res) {
      return {
        success: true,
        data: {
          data: res,
          last: last?.[0],
          next: next?.[0],
        },
      }
    }
    return {
      success: false,
      msg: '查询失败'
    }
  }

  async update(uuid: string, product: Partial<News>): Promise<News> {
    await this.entityModel.update({ uuid }, product);
    return this.entityModel.findOneBy({ uuid });
  }

  async remove(uuid: string): Promise<void> {
    await this.entityModel.update({ uuid }, { isDeleted: 1 });
  }
}
